/*
 * Copyright Thoughtworks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.thoughtworks.go.apiv1.i18n;

import com.thoughtworks.go.api.ApiController;
import com.thoughtworks.go.api.ApiVersion;
import com.thoughtworks.go.api.spring.ApiAuthenticationHelper;
import com.thoughtworks.go.spark.Routes;
import com.thoughtworks.go.spark.spring.SparkSpringController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import spark.Request;
import spark.Response;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import static spark.Spark.*;

@Component
public class I18nControllerV1 extends ApiController implements SparkSpringController {

    private final ApiAuthenticationHelper apiAuthenticationHelper;
    private final I18nService i18nService;

    // 更新支持的页面类型，与 Epic-5 保持一致，并添加 admin-environments, admin-config-xml
    private static final List<String> VALID_PAGES = Arrays.asList("site-menu", "agents", "admin-pipelines", "admin-templates", "server-config", "admin-maintenance", "admin-environments", "admin-config-xml");
    private static final List<String> VALID_LOCALES = Arrays.asList("zh", "en");

    @Autowired
    public I18nControllerV1(ApiAuthenticationHelper apiAuthenticationHelper, I18nService i18nService) {
        super(ApiVersion.v1);
        this.apiAuthenticationHelper = apiAuthenticationHelper;
        this.i18nService = i18nService;
    }

    @Override
    public String controllerBasePath() {
        return Routes.I18n.BASE;
    }

    @Override
    public void setupRoutes() {
        path(controllerBasePath(), () -> {
            before("", mimeType, this::setContentType);
            before("/*", mimeType, this::setContentType);
            // 移除认证检查，允许所有用户访问
            // before("", mimeType, this.apiAuthenticationHelper::checkUserAnd403);
            // before("/*", mimeType, this.apiAuthenticationHelper::checkUserAnd403);

            // 按页面获取翻译数据的 API
            get("", mimeType, this::getTranslationsByPage);


        });
    }

    /**
     * 按页面获取翻译数据的 API
     * 使用方式: GET /go/api/i18n?locale=zh&page=admin-pipelines
     */
    public String getTranslationsByPage(Request req, Response res) throws IOException {
        String localeParam = req.queryParams("locale");
        String pageParam = req.queryParams("page"); // 必需参数

        // 1. 验证必需参数
        if (localeParam == null || localeParam.trim().isEmpty()) {
            return renderMessage(res, 400, "Missing required parameter 'locale'");
        }

        // 2. 验证 locale 参数
        if (!VALID_LOCALES.contains(localeParam)) {
            return renderMessage(res, 400, "Parameter 'locale' must be one of: " + VALID_LOCALES);
        }

        // 3. 验证可选的 page 参数
        if (pageParam != null && !pageParam.trim().isEmpty() && !VALID_PAGES.contains(pageParam)) {
            return renderMessage(res, 400, "Parameter 'page' must be one of: " + VALID_PAGES);
        }

        try {
            // 4. 验证 page 参数是必需的
            if (pageParam == null || pageParam.trim().isEmpty()) {
                return renderMessage(res, 400, "Missing required parameter 'page'");
            }

            // 5. 调用 Service 获取指定页面的翻译数据
            I18nData translations = i18nService.getTranslationsByPage(localeParam, pageParam);

            // 6. 返回统一格式的翻译数据
            return writerForTopLevelObject(req, res, writer ->
                I18nRepresenter.toJSON(writer, translations, localeParam));

        } catch (Exception e) {
            return renderMessage(res, 500, "Internal server error: " + e.getMessage());
        }
    }

    /**
     * 旧版本 API：保持向后兼容
     */
    public String show(Request req, Response res) throws IOException {
        String localeParam = req.queryParams("locale");
        String pageParam = req.queryParams("page");

        // 验证必需参数
        if (localeParam == null || localeParam.trim().isEmpty()) {
            return renderMessage(res, 400, "Missing required parameter 'locale'");
        }

        if (pageParam == null || pageParam.trim().isEmpty()) {
            return renderMessage(res, 400, "Missing required parameter 'page'");
        }

        // 验证 locale 参数
        if (!VALID_LOCALES.contains(localeParam)) {
            return renderMessage(res, 400, "Parameter 'locale' must be one of: " + VALID_LOCALES);
        }

        // 验证 page 参数
        if (!VALID_PAGES.contains(pageParam)) {
            return renderMessage(res, 400, "Parameter 'page' must be one of: " + VALID_PAGES);
        }

        // 生成国际化消息资源
        List<I18nItem> items = generateI18nItems(localeParam, pageParam);

        return writerForTopLevelObject(req, res, writer -> I18nRepresenter.toJSON(writer, items, localeParam, pageParam));
    }

    private List<I18nItem> generateI18nItems(String locale, String page) {
        if ("site-menu".equals(page)) {
            return generateSiteMenuItems(locale);
        } else if ("agents".equals(page)) {
            return generateAgentsItems(locale);
        } else if ("admin-pipelines".equals(page)) {
            return generateAdminPipelinesItems(locale);
        }
        return Arrays.asList();
    }

    private List<I18nItem> generateSiteMenuItems(String locale) {
        if ("zh".equals(locale)) {
            return Arrays.asList(
                new I18nItem(1, "navigation.dashboard", "首页"),
                new I18nItem(2, "navigation.agents", "构建机"),
                new I18nItem(3, "navigation.materials", "源材料"),
                new I18nItem(4, "navigation.admin", "系统管理"),
                new I18nItem(5, "navigation.analytics", "分析")
            );
        } else {
            return Arrays.asList(
                new I18nItem(1, "navigation.dashboard", "Dashboard"),
                new I18nItem(2, "navigation.agents", "Agents"),
                new I18nItem(3, "navigation.materials", "Materials"),
                new I18nItem(4, "navigation.admin", "Admin"),
                new I18nItem(5, "navigation.analytics", "Analytics")
            );
        }
    }

    private List<I18nItem> generateAgentsItems(String locale) {
        if ("zh".equals(locale)) {
            return Arrays.asList(
                new I18nItem(1, "agents.tabs.static", "静态构建机"),
                new I18nItem(2, "agents.tabs.elastic", "弹性构建机"),
                new I18nItem(3, "agents.actions.enable", "启用"),
                new I18nItem(4, "agents.actions.disable", "禁用"),
                new I18nItem(5, "agents.actions.delete", "删除")
            );
        } else {
            return Arrays.asList(
                new I18nItem(1, "agents.tabs.static", "Static"),
                new I18nItem(2, "agents.tabs.elastic", "Elastic"),
                new I18nItem(3, "agents.actions.enable", "ENABLE"),
                new I18nItem(4, "agents.actions.disable", "DISABLE"),
                new I18nItem(5, "agents.actions.delete", "DELETE")
            );
        }
    }

    private List<I18nItem> generateAdminPipelinesItems(String locale) {
        if ("zh".equals(locale)) {
            return Arrays.asList(
                new I18nItem(1, "admin.pipelines.title", "流水线"),
                new I18nItem(2, "admin.pipelines.add.pipeline", "添加新流水线"),
                new I18nItem(3, "admin.pipelines.no.pipelines.message", "未定义流水线或您没有查看权限")
            );
        } else {
            return Arrays.asList(
                new I18nItem(1, "admin.pipelines.title", "Pipelines"),
                new I18nItem(2, "admin.pipelines.add.pipeline", "Add New Pipeline"),
                new I18nItem(3, "admin.pipelines.no.pipelines.message", "Either no pipelines have been defined or you are not authorized to view the same")
            );
        }
    }
}
